/*
 * queue.c
 *
 *  Created on: Jan 28, 2012
 *      Author: marco
 */

#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include "queue.h"


queue* init_queue(queue *q, pthread_mutex_t *mtx){
	q = malloc(sizeof(sizeof(queue)));

	if(q == NULL){
		return(NULL);
	}
	q->head = NULL;
	q->tail = NULL;
	q->mtx = mtx;

	return(q);
}
//VEDERE SE TENERE DENTRO O FUORI LA LOCK UNLOCK!!!
int enqueue(queue *q, void *pointer){
	queue_node *tmp;
	if(q == NULL || pointer == NULL){
		printf("ENQUEUE coda o puntatore null\n");
		return(-1);
	}
	pthread_mutex_lock(q->mtx);

	/*Inserimento in testa*/
	if(q->head == NULL){
		q->head = malloc(sizeof(queue_node));
		if(q->head == NULL){
			pthread_mutex_unlock(q->mtx);
			return(-1);
		}
		q->head->data = pointer;
		q->head->next = NULL;
		q->tail = q->head;
		pthread_mutex_unlock(q->mtx);
		return(0);
	}
	/*Inserimento in coda */
	//q->tail = tmp; //RIVEDEREEEEEEEEEE
	tmp = q->tail;
	q->tail->next = malloc(sizeof(queue_node));
	if(q->tail->next == NULL){
		pthread_mutex_unlock(q->mtx);
		return(-1);
	}
	tmp->next->data = pointer;
	tmp->next->next = NULL;
	q->tail = tmp->next;
	pthread_mutex_unlock(q->mtx);
	return(0);

}

//si assume che si abbia già il lock sulla coda
//void remove(queue *q, void *pointer){
//
//
//}




